package sfeir.ergosum.tools;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;

import android.net.Uri;

import sfeir.ergosum.model.Person;

public class ErgoSumParser {
    
    public final static String URL = "bigneotux.appspot.com";

    private String weburl;

    public ErgoSumParser(String url) {
        this.weburl = url;
    }

    public String getUrl() {
        String requestUrl = weburl;
        if (!weburl.contains(URL)) {
            requestUrl = "http://"+URL+"/vcard/" + weburl;
        }
        if (weburl.contains("/profile/")) {
            requestUrl = weburl.replace("/profile/", "/vcard/");
        }
        return requestUrl;
    }
    
    public Person getPerson() {

        String response = "";
        
        
        try {
            URLConnection connection = new URL(getUrl()).openConnection();
            response = IOUtils.toString(connection.getInputStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (response == null || !response.startsWith("BEGIN:VCARD") || !response.contains("END:VCARD")) {
            return null;
        }
        String name = weburl;
        if (weburl.contains(URL)) {
            name = Uri.parse(weburl).getLastPathSegment();
        }
        return VCardParser.parse(response, name);
    }
}
